﻿using System.Collections;
using UnityEngine;

public class EnemyEx : MonoBehaviour {
    // 血量
    public int hp = 1;

    // 分数
    public int point = 100;

    // Spaceship
    Spaceship spaceship;

    IEnumerator Start () {

        // 获取飞船脚本对象
        spaceship = GetComponent<Spaceship> ();

        // 获取玩家位置
        // Player player = FindObjectOfType<Player> ();

        // Vector2 d = player.transform.position - transform.position;

        // d = d.normalized;
        // 向玩家的方向以动
        // Move (d);

        // canShot是false的场合，结束协程
        if (spaceship.canShot == false) {
            yield break;
        }

        while (true) {

            // 获取所有子元素
            for (int i = 0; i < transform.childCount; i++) {

                Transform shotPosition = transform.GetChild (i);

                // 根据ShotPosition的角度，发射子弹
                spaceship.Shot (shotPosition);
            }

            // 等待shotDelay秒(发射间隔)
            yield return new WaitForSeconds (spaceship.shotDelay);
        }
    }

    // 移动机体
    public void Move (Vector2 direction) {
        GetComponent<Rigidbody2D> ().velocity = direction * spaceship.speed;
    }

    void OnTriggerEnter2D (Collider2D c) {
        // 获取图层名
        string layerName = LayerMask.LayerToName (c.gameObject.layer);

        // 图层名是Bullet (Player)之外的时候 什么都不执行d
        if (layerName != "Bullet (Player)") return;

        // 取得PlayerBullet的Transform
        Transform playerBulletTransform = c.transform.parent;

        // 取得Bullet组件
        Bullet bullet = playerBulletTransform.GetComponent<Bullet> ();

        // 减少hp
        hp = hp - bullet.power;

        // 删除子弹
        Destroy (c.gameObject);

        // 如果hp归零
        if (hp <= 0) {
            // 寻找分数组件，并且加分
            FindObjectOfType<Score> ().AddPoint (point);

            // 发生爆炸特效
            spaceship.Explosion ();

            // 销毁自己(敌人)
            Destroy (gameObject);

        } else {
            // 播放受到Damage动画
            spaceship.GetAnimator ().SetTrigger ("Damage");

        }
    }
}